package com.mzj.saas.sdk.withdraw.ali;

import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayFundTransToaccountTransferRequest;
import com.alipay.api.response.AlipayFundTransToaccountTransferResponse;
import com.mzj.saas.sdk.withdraw.vo.AliWithdraw;

/**
 * 支付宝转账/提现
 * 
 * @author hp
 *
 */
public class AliTransfers {

	private final static Logger logger = LoggerFactory.getLogger(AliTransfers.class);
	private static final String ALIPAY_GATEWAY_URL = "https://openapi.alipay.com/gateway.do";
	private static final String FORMAT = "json";
	private static final String CHARSET = "UTF-8";
	private static final String SIGN_TYPE = "RSA2";

	private AliWithdraw aliWithdraw;

	public AliTransfers(final AliWithdraw aliWithdraw) {
		this.aliWithdraw = aliWithdraw;
	}

	/**
	 * 获取对应的支付宝客户端对象
	 * 
	 * @return
	 */
	private AlipayClient getAlipayClient() {
		if (StringUtils.isBlank(aliWithdraw.getAppid())) {
			logger.error("AliTransfers appid is null");
			return null;
		}
		if (StringUtils.isBlank(aliWithdraw.getPrivateKey())) {
			logger.error("AliTransfers privateKey is null");
			return null;
		}
		if (StringUtils.isBlank(aliWithdraw.getPublicKey())) {
			logger.error("AliTransfers publicKey is null");
			return null;
		}
		return new DefaultAlipayClient(ALIPAY_GATEWAY_URL, aliWithdraw.getAppid(), aliWithdraw.getPrivateKey(), FORMAT,
				CHARSET, aliWithdraw.getPublicKey(), SIGN_TYPE);
	}

	/**
	 * 单笔转账
	 * <p>
	 * alipay.fund.trans.uni.transfer
	 * 接口文档地址：https://opendocs.alipay.com/apis/api_28/
	 * </p>
	 * 
	 * @return null为失败，成功则返回响应对象
	 */
	public AlipayFundTransToaccountTransferResponse toTransfers() {

		if (aliWithdraw == null) {
			logger.error("支付宝单笔转账---------->aliWithdraw is null");
			return null;
		}
		try {
			/*AlipayFundTransToaccountTransferRequest request = new AlipayFundTransToaccountTransferRequest();
			Map<String, Object> param = new HashMap<>();
			param.put("out_biz_no", aliWithdraw.getOutBizNo());
			param.put("trans_amount", aliWithdraw.getTransAmount());
			param.put("product_code", aliWithdraw.getProductCode());
			
			if (StringUtils.isNotBlank(aliWithdraw.getRemark())) {
				param.put("remark", aliWithdraw.getRemark());
            }

			Map<String, String> payeeInfo = new HashMap<>();
			payeeInfo.put("identity", aliWithdraw.getIdentity());
			payeeInfo.put("identity_type", aliWithdraw.getIdentityType());

			if (aliWithdraw.getIdentityType().equals("ALIPAY_LOGON_ID") && StringUtils.isBlank(aliWithdraw.getName())) {
				logger.error("支付宝单笔转账---------->name is null");
				return null;
			}
			param.put("payee_info", JSON.toJSONString(payeeInfo));
			request.setBizContent(JSONObject.toJSONString(param));*/
			
			// 封装参数
            Map<String, String> params = new LinkedHashMap<>();
            params.put("out_biz_no", aliWithdraw.getOutBizNo());
            params.put("payee_type", "ALIPAY_LOGONID");
            params.put("payee_account",  aliWithdraw.getIdentity());
            params.put("amount", aliWithdraw.getTransAmount().toString());
            
            if (StringUtils.isNotBlank(aliWithdraw.getName())) {
            	params.put("payee_real_name", aliWithdraw.getName());
			}
            
            AlipayFundTransToaccountTransferRequest request = new AlipayFundTransToaccountTransferRequest();
            request.setBizContent(JSONObject.toJSONString(params));

			AlipayClient alipayClient = this.getAlipayClient();
			if (alipayClient == null) {
				logger.error("[AliTransfers Fund Tranfer] Get AlipayClient Failed!");
				return null;
			}

			AlipayFundTransToaccountTransferResponse response = alipayClient.execute(request);
			if (response.isSuccess()) {
				logger.info("[AliPay Fund Tranfer Success!] Ali Response={}", JSONObject.toJSONString(response));
			} else {
				logger.error("[AliPay Fund Tranfer Failed!] Ali Response={}", JSONObject.toJSONString(response));
			}
			/*
			 * AlipayFundTransUniTransferResponse response =
			 * alipayClient.execute(request); if (response.isSuccess()) {
			 * logger.info("[AliPay Fund Tranfer Success!] Ali Response={}",
			 * JSONObject.toJSONString(response)); } else { logger.error(
			 * "[AliPay Fund Tranfer Failed!] Ali Response={}",
			 * JSONObject.toJSONString(response)); return null; }
			 */
			return response;
		} catch (Exception e) {
			logger.error("AliTransfers Service Exception = " + e, e.getMessage());
		}
		return null;
	}
}
